using System;
using System.Collections.Generic;
using System.Text;
using Dominio;
using NHibernate;
using NHibernate.Cfg;

namespace DAP
{
    public class QuestionRepository : AbstractRepository
    {
        public QuestionRepository() : base()
        {

        }

        public void createQuestion(Question question)
        {
            ISession sesion = sesiones.OpenSession();
            ITransaction transaction = sesion.BeginTransaction();
            try
            {
                sesion.Save(question);
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
                throw new HibernateException();
            }
        }
        public IList<Question> getAllFilteredQuestions(User user, int bug)
        {
            ISession sesion = sesiones.OpenSession();
            ITransaction transaction = sesion.BeginTransaction();
            try
            {
                String queryString = "from Question Question where (Question.Author = '" + user.Id + "'or Question.Destiny = '"+user.Id +"') and Question.Bug = '" + bug + "'";
               
                IQuery query = sesion.CreateQuery(queryString);
                transaction.Commit();
                return query.List<Question>();
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                throw new HibernateException();
            }
        }

        public Question getQuestionById(int id)
        {
            ISession sesion = sesiones.OpenSession();
            ITransaction transaction = sesion.BeginTransaction();
            try
            {
                IQuery query = sesion.CreateQuery("from Question where QuestionId = :x");
                query.SetString("x", id.ToString());
                transaction.Commit();
                return (Question)query.UniqueResult();
            }
            catch
            {
                transaction.Rollback();
                throw new HibernateException();
            }
        }
        
        public void createAnswer(Answer answer)
        {
            ISession sesion = sesiones.OpenSession();
            ITransaction transaction = sesion.BeginTransaction();
            try
            {
                sesion.Save(answer);
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
                throw new HibernateException();
            }
        }

    }
}
